import os
from typing import Dict, Any, List
from pathlib import Path

from shared.conversion import ConversionService
from shared.storage import StorageManager
from shared.validator import InputValidator
from shared.config import settings
from api.models.request import ConversionOptions


class ConversionHandler:
    """MCP 转换处理器"""
    
    def __init__(self):
        # 为 MCP 创建单独的存储管理器
        mcp_storage_path = settings.storage_path / "mcp"
        self.storage_manager = StorageManager(mcp_storage_path, settings.file_ttl)
        self.conversion_service = ConversionService(self.storage_manager)
    
    async def handle_convert_markdown_to_ppt(self, arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
        """处理 Markdown 内容转换"""
        try:
            markdown_content = arguments.get("markdown_content")
            if not markdown_content:
                return [{"type": "text", "text": "❌ Markdown content is required"}]
            
            theme = arguments.get("theme", settings.default_theme)
            output_filename = arguments.get("output_filename")
            image_width_ratio = arguments.get("image_width_ratio", settings.default_image_width_ratio)
            
            # 创建转换选项
            options = ConversionOptions(
                theme=theme,
                image_width_ratio=image_width_ratio
            )
            
            # 执行转换
            result = await self.conversion_service.convert_content(
                markdown_content,
                options,
                output_filename
            )
            
            # 获取文件的绝对路径
            file_data = await self.conversion_service.get_file(result.file_id)
            if file_data:
                content, _ = file_data
                # 保存到本地文件
                output_path = Path.cwd() / result.filename
                with open(output_path, 'wb') as f:
                    f.write(content)
                
                return [
                    {
                        "type": "text",
                        "text": f"✅ Successfully converted Markdown to PowerPoint presentation!\n\n"
                               f"📄 **Output file**: {result.filename}\n"
                               f"📊 **Slides count**: {result.pages_count}\n"
                               f"📦 **File size**: {result.file_size:,} bytes ({result.file_size / 1024:.1f} KB)\n"
                               f"🎨 **Theme**: {theme}\n"
                               f"📍 **Location**: {output_path.absolute()}\n\n"
                               f"The presentation has been saved to your current working directory."
                    }
                ]
            else:
                return [
                    {
                        "type": "text",
                        "text": "❌ Conversion completed but file could not be retrieved."
                    }
                ]
                
        except Exception as e:
            return [
                {
                    "type": "text",
                    "text": f"❌ Conversion failed: {str(e)}"
                }
            ]
    
    async def handle_convert_markdown_file_to_ppt(self, arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
        """处理 Markdown 文件转换"""
        try:
            file_path = arguments.get("file_path")
            if not file_path:
                return [{"type": "text", "text": "❌ File path is required"}]
                
            theme = arguments.get("theme", settings.default_theme)
            output_filename = arguments.get("output_filename")
            image_width_ratio = arguments.get("image_width_ratio", settings.default_image_width_ratio)
            
            # 验证文件路径
            if not os.path.exists(file_path):
                return [
                    {
                        "type": "text",
                        "text": f"❌ File not found: {file_path}"
                    }
                ]
            
            # 创建转换选项
            options = ConversionOptions(
                theme=theme,
                image_width_ratio=image_width_ratio
            )
            
            # 执行转换
            result = await self.conversion_service.convert_file(
                file_path,
                options,
                output_filename
            )
            
            # 获取文件并保存到本地
            file_data = await self.conversion_service.get_file(result.file_id)
            if file_data:
                content, _ = file_data
                # 保存到输入文件的同目录
                input_path = Path(file_path)
                output_path = input_path.parent / result.filename
                
                with open(output_path, 'wb') as f:
                    f.write(content)
                
                return [
                    {
                        "type": "text",
                        "text": f"✅ Successfully converted Markdown file to PowerPoint!\n\n"
                               f"📥 **Input file**: {input_path.name}\n"
                               f"📄 **Output file**: {result.filename}\n"
                               f"📊 **Slides count**: {result.pages_count}\n"
                               f"📦 **File size**: {result.file_size:,} bytes ({result.file_size / 1024:.1f} KB)\n"
                               f"🎨 **Theme**: {theme}\n"
                               f"📍 **Location**: {output_path.absolute()}\n\n"
                               f"The presentation has been saved to the same directory as the input file."
                    }
                ]
            else:
                return [
                    {
                        "type": "text",
                        "text": "❌ Conversion completed but file could not be retrieved."
                    }
                ]
                
        except Exception as e:
            return [
                {
                    "type": "text",
                    "text": f"❌ File conversion failed: {str(e)}"
                }
            ]
    
    async def handle_get_supported_themes(self, _: Dict[str, Any]) -> List[Dict[str, Any]]:
        """获取支持的主题列表"""
        themes_info = []
        for theme in settings.supported_themes:
            marker = "🎯" if theme == settings.default_theme else "🎨"
            themes_info.append(f"{marker} **{theme}**" + (" (default)" if theme == settings.default_theme else ""))
        
        return [
            {
                "type": "text",
                "text": f"🎨 **Supported PowerPoint Themes:**\n\n" + "\n".join(themes_info) + 
                       f"\n\n💡 Use any of these themes with the `theme` parameter when converting."
            }
        ]
    
    async def handle_validate_markdown(self, arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
        """验证 Markdown 内容"""
        try:
            markdown_content = arguments.get("markdown_content")
            if not markdown_content:
                return [{"type": "text", "text": "❌ Markdown content is required"}]
            
            # 执行验证
            is_valid, error_msg = InputValidator.validate_markdown_content(markdown_content)
            
            if is_valid:
                # 分析内容统计
                lines = markdown_content.split('\n')
                char_count = len(markdown_content)
                word_count = len(markdown_content.split())
                
                # 统计标题
                h1_count = len([line for line in lines if line.strip().startswith('# ')])
                h2_count = len([line for line in lines if line.strip().startswith('## ')])
                h3_count = len([line for line in lines if line.strip().startswith('### ')])
                
                # 统计列表项
                list_items = len([line for line in lines if line.strip().startswith('- ')])
                
                # 统计图片和视频
                import re
                images = len(re.findall(r'!\[.*?\]\(.*?\)', markdown_content))
                
                return [
                    {
                        "type": "text",
                        "text": f"✅ **Markdown content is valid for conversion!**\n\n"
                               f"📊 **Content Statistics:**\n"
                               f"• Characters: {char_count:,}\n"
                               f"• Words: {word_count:,}\n"
                               f"• Lines: {len(lines):,}\n\n"
                               f"📋 **Structure Analysis:**\n"
                               f"• H1 headings (title slides): {h1_count}\n"
                               f"• H2 headings (content slides): {h2_count}\n"
                               f"• H3 headings (sub-content): {h3_count}\n"
                               f"• List items: {list_items}\n"
                               f"• Images/Videos: {images}\n\n"
                               f"🎯 **Estimated slides**: {h1_count + h2_count + h3_count}"
                    }
                ]
            else:
                return [
                    {
                        "type": "text",
                        "text": f"❌ **Markdown validation failed:**\n\n{error_msg}\n\n"
                               f"Please fix the issues and try again."
                    }
                ]
                
        except Exception as e:
            return [
                {
                    "type": "text",
                    "text": f"❌ Validation error: {str(e)}"
                }
            ]